import sys
import json

def calculate_settlement(formula, **kwargs):
    """动态计算结算金额"""
    try:
        allowed_names = {k: v for k, v in kwargs.items()}
        # 替换 kwargs 中的 None 为 Python 的 None，以便 eval 函数可以正确处理
        kwargs = {k: v if v is not None else None for k, v in kwargs.items()}
        return eval(formula, {"__builtins__": {}}, allowed_names)
    except Exception as e:
        print(f"Error in calculate_settlement: {str(e)}", file=sys.stderr)
        raise  # 重新抛出异常，确保退出码为 1

if __name__ == "__main__":
    try:
        # 从文件中读取输入数据
        if len(sys.argv) < 2:
            print("Usage: python settlement.py <input_file>", file=sys.stderr)
            sys.exit(1)

        input_file = sys.argv[1]
        with open(input_file, "r") as f:
            input_data = json.load(f)

        # 打印解析后的输入数据
        print(f"Parsed input: {input_data}", file=sys.stderr)

        formula = input_data["formula"]
        order_amount = input_data["order_amount"]
        tax_rate = input_data["tax_rate"]
        commission_rate = input_data["commission_rate"]
        bonus_amount = input_data.get("bonus_amount", 0)  # 提供默认值 0
        discount_rate = input_data.get("discount_rate", 1)  # 提供默认值 1

        # 动态计算结算金额
        result = calculate_settlement(formula, orderAmount=order_amount, taxRate=tax_rate,
                                      commissionRate=commission_rate, bonusRate=bonus_amount,
                                      discountRate=discount_rate)

        # 输出结果
        print(json.dumps({"settlement_amount": result}))
    except json.JSONDecodeError as e:
        print(f"Error in main: Failed to decode JSON input: {str(e)}", file=sys.stderr)
        sys.exit(1)
    except Exception as e:
        print(f"Error in main: {str(e)}", file=sys.stderr)
        sys.exit(1)
